package com.Sing.Controller;

import com.Sing.Pojo.Book;
import com.Sing.Pojo.Lend;
import com.Sing.Pojo.Reader;
import com.Sing.Pojo.Type;
import com.Sing.Service.BookService;
import com.Sing.Service.LendService;
import com.Sing.Service.ReaderService;
import com.Sing.Service.TypeService;
import com.Sing.Utils.Constant;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.http.HttpRequest;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

@Controller
public class LendController {
    private LendService lendService;
    @Autowired
    @Qualifier("lendServiceImpl")
    public void setLendService(LendService lendService) {
        this.lendService = lendService;
    }

    private ReaderService readerService;
    @Autowired
    @Qualifier("readerServiceImpl")
    public void setReaderService(ReaderService readerService) {
        this.readerService = readerService;
    }

    private BookService bookService;
    @Autowired
    @Qualifier("bookServiceImpl")
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }


    // 跳转到 借阅管理 的页面
    @RequestMapping("/lendListIndex")
    public String lendListIndexJump(){

        return "lend/lendListIndex";
    }

    // 根据条件查询表数据，并返回给页面
    @RequestMapping("/lendListAll")
    @ResponseBody
    public HashMap<Object,Object> lendListAll( String readerNumber, String name,
                                               Integer backType, Integer status,
                                               String limit, String page ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        // 處理 limit (頁面大小) 和 page (起始位置)
        int pageSize = Integer.parseInt( limit );
        int pageContext = ( Integer.parseInt( page ) - 1 ) * pageSize;

        // 初始化四個參數的值
        String readerNumberTemp = null, nameTemp = null;
        int backTypeTemp = -1, statusTemp = -1;

        // 對於 name 和 readerNumber 而言，如果 readerNumberTemp 和 nameTemp 不爲空，就繼承對應的值，否則就為 Null
        if ( readerNumber != null && ! readerNumber.equals("") ){
            readerNumberTemp = "%" + readerNumber + "%";
        }

        if ( name != null && ! name.equals("") ){
            nameTemp = "%" + name + "%";
        }

        // 初始化 backType 和 status 的值，避免出現 空指針異常
        if ( backType == null || backType <= -1 ){
            backType = -1;
        }
        if ( status == null || status <= -1 ){
            status = -1;
        }

        // 對於 backTypeTemp 和 statusTemp 而言，如果 backType 和 backType 大於 0，就可以繼承對飲的值，否則就爲 -1
        if ( backType >= 0 ){
            backTypeTemp = backType;
        }

        if ( status >= 0 ){
            statusTemp = status;
        }

        ArrayList<Lend> lendArrayList = lendService.queryDataByCheck( readerNumberTemp, nameTemp, backTypeTemp, statusTemp, pageSize, pageContext );
        int count = lendService.queryCountByCheck( readerNumberTemp, nameTemp, backTypeTemp, statusTemp );

        resultMap.put( "data", lendArrayList );
        resultMap.put( "code", "0" );
        resultMap.put( "count", count );
        return resultMap;
    }

    // 還書
    @RequestMapping( "/backLendListByIds" )
    @ResponseBody
    public HashMap<Object,Object> backLendByIds( String ids, String bookIds ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        String[] idsTemp = {""}, bookIdsTemp = {""};

        // 拆分 ids 和 bookIds
        idsTemp = ids.split( "," );
        bookIdsTemp = bookIds.split( "," );

        // 執行修改
        for ( int i = 0; i < idsTemp.length; i++ ){
            HashMap<String, Object> paramMap = new HashMap<>();

            //將需要的參數甩到 paramMap 中
            paramMap.put( "id", Integer.parseInt( idsTemp[ i ] ) );
            paramMap.put( "bookId", Integer.parseInt( bookIdsTemp[ i ] ) );
            paramMap.put( "backDate", new Date() );

            boolean flag = lendService.modifyStatus(paramMap);
        }

        resultMap.put( "code", "0" );
        return resultMap;
    }

    // 跳轉到借書界面
    @RequestMapping("/addLendList")
    public String addLendListJump(){
//        // 查詢出 Type 表中的數據，並傳遞到前端頁面中
//        ArrayList<Type> typeInfo = typeService.getAllData();
//        model.addAttribute( "typeInfo", typeInfo );
        return "lend/addLendList";
    }

    // 借書
    @RequestMapping("/addLend")
    @ResponseBody
    public HashMap<Object,Object> addLend( String readerNumber, String ids ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        // readerNumber 是借書卡， ids 是所借圖書的 bookId 構成的字符串
        // 拆分 Ids 為一個個 bookId
        String[] bookIds = ids.split(",");

        // 獲取 readerId
        Reader reader = readerService.queryReaderByReaderNumber( readerNumber );
        int readerId = reader.getId();

        // 借書
        for ( String bookId : bookIds ){

            // 獲取 bookId 對應的圖書，方便查看是否被借出
            Book book = bookService.queryBookById(Integer.parseInt(bookId));

            // 判斷書籍是否可以借出，如果已經被借出就不能再借了
            if ( book.getStatus() == 0 ) {
                // 將數據存入 paramMap
                HashMap<String, Object> paramMap = new HashMap<>();
                paramMap.put( "bookId", Integer.parseInt( bookId ) );
                paramMap.put( "readerId", readerId );
                paramMap.put( "lendDate", new Date() );

                // 執行添加借閲記錄
                boolean flag = lendService.insertData(paramMap);

                // 將 book 表中的對應數據修改為 借出
                bookService.modifyStatus( 1, Integer.parseInt( bookId ) );

            } else {

                resultMap.put( "code", 1 );
                resultMap.put( "msg", "所選書籍中存在被借出的書籍" );
                return resultMap;

            }

        }

        resultMap.put( "code", "0" );
        return resultMap;
    }

    // 刪除借書記錄
    @RequestMapping("/deleteLendListByIds")
    @ResponseBody
    public HashMap<Object,Object> deleteBookDate( String ids ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        // 將 ids 拆分為一個字符串數組
        String[] tempIds = ids.split(",");

        for ( String id : tempIds ){
            boolean flag = false;
            if ( id != null ){
                flag = lendService.deleteData( Integer.parseInt( id ) );
            }

            // 儅刪除失敗時，將 code = 1 存入 Map ，代表函數執行失敗
            if ( ! flag ){
                resultMap.put( "code", "1" );
                return resultMap;
            }
        }

        resultMap.put( "code", "0" );
        return resultMap;
    }

    // 跳轉到異常還書的界面
    @RequestMapping("/excBackBook")
    public String exBackBookJump( String id, HttpServletRequest req ){

        // 將獲取到的 Id 存放入 Session 中，讓後續可以取用
        req.getSession().setAttribute( Constant.LendId, id );

        return "lend/excBackBook";
    }

    // 異常還書
    @RequestMapping("/updateLendInfoSubmit")
    @ResponseBody
    public HashMap<Object,Object> abnormalBackSubmit( String backType, String remarks, HttpServletRequest req ){
        HashMap<Object, Object> resultMap = new HashMap<>();
        HashMap<Object, Object> paramMap = new HashMap<>();

        // 取出存在 Session 中的值，並將其銷毀
        String temp = ( String ) req.getSession().getAttribute( Constant.LendId );
        Integer id = null;
        // 如果 temp 不爲空説明數據被成功取出，否則就中止程序的運行
        if ( temp != null ){
            id = Integer.parseInt( temp );
            req.getSession().removeAttribute( Constant.LendId );
        } else {
            resultMap.put( "code", "1" );
            resultMap.put( "msg", "fill" );
            return resultMap;
        }

        // 將 backType 轉換為 Integer 類型
        Integer backTypeTemp = null;
        if ( backType != null ){
            backTypeTemp = Integer.parseInt( backType );
        }

        paramMap.put( "id", id );
        paramMap.put( "backType", backTypeTemp );
        paramMap.put( "exceptRemarks", remarks );

        boolean flag = lendService.updateDataById( paramMap );

        if ( flag ){
            resultMap.put( "code", "0" );
        } else {
            resultMap.put( "code", "1" );
            resultMap.put( "msg", "fill" );
        }

        return resultMap;
    }

    @RequestMapping("/queryLookBookList2")
    public String queryLookBookListJump( Model model, HttpServletRequest req ){

        // 從 Session 中獲取當前登錄的用戶數據
        Reader reader = ( Reader ) req.getSession().getAttribute( Constant.USER_SESSION );

        ArrayList<Lend> lendArrayList = lendService.queryLendListByReaderId( reader.getId() );
        req.getSession().setAttribute( "info", lendArrayList );

        return "lend/lookBookList";
    }
}
